import Mock from "mockjs";
const total = 20;
const tableData = Mock.mock({
  "data|20": [
    {
      "id|+1": 1,
      name: "@cword(5, 10)",
      email: "@email",
      role: "@cword(3,5)",
      updateTime: "@datetime",
    },
  ],
});
// 获取表格数据
Mock.mock(/\/api\/table.*/, "get", (options: any) => {
  const url = new URL(options.url, "http://xxxx.com");
  const currentPage = parseInt(url.searchParams.get("currentPage") || "1");
  const pageSize = parseInt(url.searchParams.get("pageSize") || "10");
  const start = (currentPage - 1) * pageSize;
  const end = start + pageSize;
  const list = tableData.data.slice(start, end);
  return {
    code: 200,
    message: "获取表格数据成功",
    list,
    total,
    currentPage,
    pageSize,
  };
});

// 添加表格数据
Mock.mock("/api/table/add", "post", (options) => {
  const newVal = JSON.parse(options.body);
  if (newVal.name && newVal.password && newVal.email && newVal.role) {
    newVal.updateTime = Mock.Random.datetime();
    tableData.data.push(newVal);
    return {
      code: 200,
      message: "添加成功",
    };
  } else {
    return {
      code: 400,
      message: "添加失败",
    };
  }
});

// 批量删除表格数据
Mock.mock("/api/table/all", "delete", (options) => {
  const { ids } = JSON.parse(options.body);
  if (ids && ids.length > 0) {
    // 过滤掉要删除的数据
    tableData.data = tableData.data.filter((item: any) => {
      return !ids.some((selected: any) => selected.id === item.id);
    });
    return {
      code: 200,
      message: "删除成功",
    };
  }
  return {
    code: 400,
    message: "删除失败",
  };
});

// 删除单行数据
Mock.mock("/api/table", "delete", (options) => {
  const { id } = JSON.parse(options.body);
  console.log(id);
  if (id) {
    const index = tableData.data.findIndex((item: any) => item.id === id);
    if (index > -1) {
      tableData.data.splice(index, 1);
      return {
        code: 200,
        message: "删除成功",
      };
    }
  }
  return {
    code: 400,
    message: "删除失败",
  };
});

// 更新表格数据
Mock.mock("/api/table/put", "put", (options) => {
  const { id, data } = JSON.parse(options.body);
  if (id) {
    const index = tableData.data.findIndex((item: any) => item.id === id);
    if (index > -1) {
      tableData.data[index] = {
        ...tableData.data[index],
        ...data,
        updateTime: Mock.Random.datetime(),
      };
      return {
        code: 200,
        message: "更新成功",
      };
    }
  }
  return {
    code: 400,
    message: "更新失败",
  };
});
